package com.zixuan.sina.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zixuan.sina.dao.CommentMapper;
import com.zixuan.sina.entity.Comment;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.entity.vo.CommentVo;
import com.zixuan.sina.service.CommentService;
import com.zixuan.sina.service.UserService;
import com.zixuan.sina.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Resource
    private UserService userService;
    @Override
    public Result listComment(Comment comment) {
        List<CommentVo> result=new ArrayList<>();
        if(comment.getPostId()==null){
            return Result.error().message("请选择文章");
        }


        List<Comment> commentList = baseMapper.selectList(new QueryWrapper<Comment>().eq("post_id", comment.getPostId()));
        List<Comment> res=getData(commentList,"-1L");

        result = getCommentVOs(res);

        return Result.ok(result);
    }



    public  List<CommentVo>  listComment(String postId) {
        List<CommentVo> result=new ArrayList<>();

        List<Comment> commentList = baseMapper.selectList(new QueryWrapper<Comment>().eq("post_id", postId));
        List<Comment> res = baseMapper.selectList(new QueryWrapper<Comment>().eq("post_id", postId).eq("parent_id","-1"));
        System.out.println("顶级评论：\n"+res);
        List<Comment> commentResult=new ArrayList<>();
        for (Comment comment : res) {
            comment.setChildren(getData(commentList,comment.getCommentId()));
            commentResult.add(comment);
        }
        result = getCommentVOs(commentResult);
        return result;
    }

    @Override
    public Result add(Comment comment) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(null==user){
            throw new AccountExpiredException("当前尚未登录");
        }
        comment.setUserId(user.getId());
        if(comment.getParentId()==null){
            comment.setParentId("-1");
        }
        int row = baseMapper.insert(comment);
        if(row<=0){
            return Result.error().message("评论失败");
        }
        return Result.ok().message("操作成功");
    }

    @Override
    public Result delComment(String commentId) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long count = baseMapper.selectCount(new QueryWrapper<Comment>().eq("parent_id", commentId));
        if(count>0)
        {
            return Result.error().message("当前评论下存在评论,不允许删除");
        }
        Comment comment = baseMapper.selectById(commentId);
        if(!comment.getUserId().equals(principal.getId())){
            return Result.error().message("只能删除自己的评论哦");
        }
        boolean row = removeById(commentId);
        if (!row) return Result.error().message("删除失败");
        return Result.ok().message("删除成功");
    }

    private List<CommentVo> getCommentVOs(List<Comment> res) {
        List<CommentVo> result=new ArrayList<>();
        for (Comment re : res) {
            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(re,commentVo);
            User userById = userService.findUserById(re.getUserId());
            if(re.getResId()!=null){
                User resUser = userService.findUserById(re.getResId());
                if(resUser!=null){
                    commentVo.setResId(re.getResId());
                    commentVo.setResName(resUser.getNickName());
                }
            }

            commentVo.setNickName(userById.getNickName());
            commentVo.setAvatar(userById.getAvatar());


            if(re.getChildren().size()>0){//如果存在下级关系
//                commentVo.setChildren(getCommentVOs(re.getChildren()));
                List<CommentVo> childrens=new ArrayList<>();
                for (Comment child : re.getChildren()) {
                    CommentVo childrenVo = new CommentVo();
                    BeanUtils.copyProperties(child,childrenVo);
                    User children = userService.findUserById(child.getUserId());
                    if(ObjectUtil.isNull(children)){
                        continue;
                    }
                    if(child.getResId()!=null){
                        User childrenResUser = userService.findUserById(child.getResId());
                        if(childrenResUser!=null){
                            childrenVo.setResId(child.getResId());
                            childrenVo.setResName(childrenResUser.getNickName());
                        }
                    }


                    if(StrUtil.isNotBlank(children.getNickName())){
                        childrenVo.setNickName(children.getNickName());
                    }

                    childrenVo.setAvatar(children.getAvatar());
                    childrens.add(childrenVo);
                }
                commentVo.setChildren(childrens);
            }
            result.add(commentVo);
        }
        return result;
    }

    private List<Comment> getData(List<Comment> commentList, String id) {
        List<Comment> res=new ArrayList<>();
        for (Comment comment : commentList) {
            if(comment!=null && comment.getParentId().equals(id)){
//                comment.setChildren(this.getData(commentList,comment.getCommentId()));
                res.add(comment);

            }

        }
        return res;
    }


}
